package com.sparkseries.common.security.handler;

import com.sparkseries.common.security.exception.CustomException;
import com.sparkseries.common.security.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 退出成功处理器
 */
@Component
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JwtUtil jwtUtil;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String jwt = request.getHeader("Authorization");

        if (jwt.isEmpty()) {
            throw new CustomException();
        }

        if (!jwtUtil.verifyToken(jwt)) {
            throw new CustomException();
        }

        // 从Redis中删除Token对象
        stringRedisTemplate.delete("loginToken:" + jwt);
    }
}
